import 'dart:io';
import 'dart:typed_data';
import 'package:device_info_plus/device_info_plus.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:image_picker/image_picker.dart';
import 'package:kmxy_base/kmxy_base.dart';
import 'package:kmxy_base/media_select/cat_img_video_page_view.dart';
import 'package:kmxy_base/media_select/media_select_view.dart';
import 'package:kmxy_base/media_select/media_type.dart';
import 'package:kmxy_base/network/net.dart';
import 'package:kmxy_base/util/string_util.dart';
import 'package:kmxy_base/widget/camera.dart';
import 'package:path_provider/path_provider.dart';
import 'package:external_path/external_path.dart';
import 'package:image/image.dart' as imgAS;

class FileUtil {
  /// 获取APP下文件路径
  /// Android:  getFilesDir
  /// iOS:  NSApplicationSupportDirectory
  static Future<String> getFilesDir() async {
    Directory filesDir = await getApplicationSupportDirectory();
    return filesDir.path;
  }

  /// 获取APP下缓存路径
  /// Android:  NSCachesDirectory
  /// iOS:  getCacheDir
  static Future<String> getCacheDir() async {
    Directory cacheDir = await getTemporaryDirectory();
    return cacheDir.path;
  }

  // 获取外部Download文件夹路径
  static Future<String> getExternalDownloadPath() async {
    Directory? downloadDir = await getDownloadsDirectory();
    if (downloadDir == null) return '';
    return downloadDir.path;
  }

  /// 保存图片和视频到相册中
  /// Android：
  ///     在 AndroidManifest.xml 文件中添加
  ///     <application android:requestLegacyExternalStorage="true" .....>
  ///     获取存储权限storage
  ///
  /// iOS：
  ///     在 Info.plist 文件中添加
  ///     <key>NSPhotoLibraryAddUsageDescription</key>
  ///     <string>请求添加图片到相册</string>
  ///     获取写入相册权限photosAddOnly
  ///
  /// 权限申请详情，请查看：permission_util.dart 文件
  static saveImgOrVideoToGallery(filePath,
      {bool isDelSourceFile = false}) async {
    await ImageGallerySaver.saveFile(filePath);
    if (isDelSourceFile) {
      File(filePath).delete();
    }
  }

  static saveFileDownload(String content, String fileName) async {
    String externalDownloadPath =
        await ExternalPath.getExternalStoragePublicDirectory(
            ExternalPath.DIRECTORY_DOWNLOAD);
    File file = File('$externalDownloadPath/$fileName');
    await file.writeAsString(content);
  }

  /// 获取文件名字
  static String getFileNameOnly(String filePath) {
    if (filePath.isEmpty) return '';
    return filePath.substring(
        filePath.lastIndexOf('/') + 1, filePath.lastIndexOf('.'));
  }

  /// 获取文件名字，包括后缀
  static String getFileName(String filePath) {
    if (filePath.isEmpty) return '';
    if (filePath.contains('?')) {
      return filePath.substring(
          filePath.lastIndexOf('/') + 1, filePath.lastIndexOf('?'));
    }
    return filePath.substring(filePath.lastIndexOf('/') + 1, filePath.length);
  }

  /// 获取文件名后缀
  static String getFileSuffix(String filePath) {
    if (filePath.isEmpty) return '';
    return filePath.substring(filePath.lastIndexOf('.') + 1, filePath.length);
  }

  static List<String> diyCameraList = [];

  /// 从相册或者相机获取图片和视频
  /// type : 0、相机图片，1、相册图片，2、相机视频，3、相册视频
  static Future<XFile?> getImageOrVideo(BuildContext context, int type,
      {int imageQuality = 70, double? maxWidth, double? maxHeight}) async {
    final deviceInfoPlugin = DeviceInfoPlugin();
    final deviceInfo = await deviceInfoPlugin.deviceInfo;
    final map = deviceInfo.toMap();
    switch (type) {
      case 0:
        if (diyCameraList.contains(map['androidId'])) {
          String? path = await CameraUtil.openCamera(
              context, imageQuality, maxWidth, maxHeight);
          return path == null ? null : XFile(path);
        } else {
          return ImagePicker().pickImage(
              source: ImageSource.camera, imageQuality: imageQuality);
        }
      case 1:
        return ImagePicker()
            .pickImage(source: ImageSource.gallery, imageQuality: imageQuality);
      case 2:
        return ImagePicker().pickVideo(source: ImageSource.camera);
      case 3:
        return ImagePicker().pickVideo(source: ImageSource.gallery);
      default:
        return Future.value(null);
    }
  }

  /// Uint8List转图片文件
  static Future<String> uint8List2File(Uint8List imageByte) async {
    String dirPath = await getCacheDir();
    //生成file文件格式
    var file =
        await File('$dirPath/image_${DateTime.now().millisecond}.png').create();
    //转成file文件
    file.writeAsBytesSync(imageByte);
    return file.path;
  }

  /// 文件查看
  static fileCat(
      BuildContext context, String url, MediaUrlMakeFun mediaUrlMakeFun) async {
    if (MediaType.imgSuffixList
            .contains(FileUtil.getFileSuffix(url).toLowerCase()) ||
        MediaType.videoSuffixList
            .contains(FileUtil.getFileSuffix(url).toLowerCase())) {
      Navigator.push(context, MaterialPageRoute(
        builder: (_) {
          return CatImgVideoPageView(dataList: [
            {'link': url},
          ], index: 0, mediaUrlMakeFun: mediaUrlMakeFun);
        },
      ));
    } else {
      FocusManager.instance.primaryFocus?.unfocus();
      String fileDir = await FileUtil.getFilesDir();
      File file = File('$fileDir/${FileUtil.getFileName(url)}');
      // 文件是否已经下载到本地
      if (file.existsSync()) {
        // 使用wps打开
        bool isAvilible = await KmxyBase.isAvilible('cn.wps.moffice_eng');
        if (isAvilible) {
          await KmxyBase.openWps(file.path);
        } else {
          return '请安装 WPS Office，再查看文件'.toast();
        }
      } else {
        EasyLoading.show(status: '下载中...');
        Net.downloadTemp(
            mediaUrlMakeFun(url), '$fileDir/${FileUtil.getFileName(url)}',
            progress: (int progress) {}, finish: (String savePath) async {
          EasyLoading.dismiss();
          // 使用wps打开
          bool isAvilible = await KmxyBase.isAvilible('cn.wps.moffice_eng');
          if (isAvilible) {
            await KmxyBase.openWps(savePath);
          } else {
            return '请安装 WPS Office，再查看文件'.toast();
          }
        }, error: (e) {
          EasyLoading.dismiss();
        });
      }
    }
  }

  static Future<File> compressImageWithDart(String srcPath, String outPath,
      {int quality = 60, int minHeight = 1920, int minWidth = 1080}) async {
    // 1. 读取图片
    final File imageFile = File(srcPath);
    final Uint8List imageBytes = await imageFile.readAsBytes();
    imgAS.Image? image = imgAS.decodeImage(imageBytes);

    // 2. 缩放图片（按比例缩小到 1080p）
    if (image != null) {
      image = imgAS.copyResize(
        image,
        width: minWidth, // 目标宽度，高度自动按比例计算
        height: minHeight,
      );
    }

    // 3. 质量压缩（JPG 格式）
    final Uint8List compressedBytes = imgAS.encodeJpg(image!, quality: quality);

    // 4. 保存文件
    final String destPath = outPath;
    final File compressedFile = File(destPath);
    await compressedFile.writeAsBytes(compressedBytes);
    return compressedFile;
  }
}
